package com.htsk.city.services.admin.service;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.htsk.city.services.admin.params.LoginUser;
import com.htsk.city.services.admin.vo.LoginUserBackVO;
import com.htsk.city.services.core.constant.HttpStatus;
import com.htsk.city.services.core.dao.MenuDao;
import com.htsk.city.services.core.dao.SysUserDao;
import com.htsk.city.services.core.dao.SysUserRoleDao;
import com.htsk.city.services.core.domain.Menu;
import com.htsk.city.services.core.domain.Role;
import com.htsk.city.services.core.domain.SysUser;
import com.htsk.city.services.core.entity.R;
import com.htsk.city.services.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户服务
 */
@Service
@Slf4j
public class UserService {
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private MenuDao menuDao;

    /**
     * 校验当前登录用户是否满足角色权限
     * @param role 所需角色
     */
    public void checkRole(String role) {
        SysUser sysUser=JSONUtil.toBean(StpUtil.getLoginIdAsString(),SysUser.class);
        List<Role>  sysRoleList = sysUserRoleDao.queryByUser(sysUser.getId());boolean exists = sysRoleList.stream()
                .anyMatch(p -> role.equals(p.getRoleKey()));
        if (!exists){
            throw new ServiceException("当前角色没有权限", HttpStatus.FORBIDDEN);
        }
    }

    /**
     * 查询用户资源权限
     * @param sysUser 当前用户
     * @return
     */
    public R<List<String>> permissionList(SysUser sysUser){
        List<Menu> sysMenuList=menuDao.queryByUser(sysUser.getId());
        return R.ok(sysMenuList.stream().map(Menu::getPerms).collect(Collectors.toList()));
    }

    /**
     * 登录
     * @param loginUser 登录参数
     * @return LoginUserBackVO 登录用户
     */
    public R<LoginUserBackVO> login(LoginUser loginUser){
        SysUser sysUser=sysUserDao.findByUsernameOrMobile(loginUser.getAccount(), loginUser.getAccount());
        if (sysUser==null||sysUser.getDelFlag()==1){
            return R.fail("用户不存在");
        }
        if (!sysUser.getPassword().equals(loginUser.getPassword())){
            return R.fail("用户名/密码错误");
        }
        if(sysUser.getStatus()==0){
            return R.fail("状态异常，联系管理员");
        }
        StpUtil.login(JSONUtil.toJsonStr(sysUser),loginUser.getClient());

        return R.ok(new LoginUserBackVO(sysUser));

    }
}
